package com.example.hello.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.utils.DateUtil;
import com.example.hello.authentication.JWTToken;
import com.example.hello.authentication.JWTUtil;
import com.example.hello.authentication.ShiroUtil;
import com.example.hello.authentication.ShiroConstant;
import com.example.hello.entity.User;
import com.example.hello.po.UserPo;
import com.example.hello.service.PermissionService;
import com.example.hello.service.RoleService;
import com.example.hello.service.UserService;
import com.example.common.utils.result.ResultBO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 封装User相关方法
 * </p>
 *
 * @author 12071
 * @date 2022/7/22 17:03
 */
@Slf4j
@Service
public class UserManager {


    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    public ResultBO listUsersInfo() {
        List<UserPo> userList = userService.getUserList();
        for (UserPo user : userList) {
            Set<String> permissions = permissionService.getPermissionsByRole(user.getRole());
            user.setPermissions(permissions);
        }
        return ResultBO.ok(userList);
    }

    public UserPo getUserInfoByName(String userName) {
        UserPo user = userService.getUserByName(userName);
        user.setPermissions(permissionService.getPermissionsByRole(user.getRole()));
        return user;
    }

    public User getUserByName(String userName) {
        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getName, userName));
        return one;
    }

    public String getPasswordByName(String userName) {
        return userService.getPasswordByUser(userName);
    }

    public ResultBO login(String username, String password) {
        username = StringUtils.lowerCase(username);
        // TODO: 密码应加密,暂时先明文
//        password = MD5Util.encrypt(username, password);
        log.info("userName: {}, password: {}", username, password);
        User user = getUserByName(username);
        if (user == null) {
            return ResultBO.error("用户不存在");
        }
        if (!StringUtils.equals(password, user.getPassword())) {
            return ResultBO.error("用户名或密码错误");
        }
        // TODO: 更新User登录时间

        // TODO: 添加登录日志 LoginLog 到 DB


        String token = JWTUtil.sign(username, password);
        LocalDateTime expireTime = LocalDateTime.now().plusSeconds(ShiroConstant.JWT_TIMEOUT/1000);
        String expireTimeStr = DateUtil.formatFullTime(expireTime);
        JWTToken jwtToken = new JWTToken(token, expireTimeStr);
        // TODO: token加密/解密
        String key = ShiroConstant.USER_LOGIN_TOKEN_PREFIX + jwtToken.getToken();
        redisTemplate.opsForValue().set(key, jwtToken.getToken(), ShiroConstant.JWT_TIMEOUT, TimeUnit.MILLISECONDS);

        return ResultBO.ok("通过认证，token: 【" + jwtToken.getToken() + "】");

    }

    public ResultBO logout() {
        ShiroUtil.getSubject().logout();
        return ResultBO.ok("logout success");
    }
}
